package com.xb.system.service.impl;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.*;
import java.util.UUID;
@Service
public class LocalFileStorageService {
    @Value("${file.upload.path:E:/uploads/original/}")
    private String originalUploadDir;

    @Value("${file.output.path:E:/uploads/result/}")
    private String resultOutputDir;

    @PostConstruct
    public void init() {
        File originalDir = new File(originalUploadDir);
        File resultDir = new File(resultOutputDir);
        if (!originalDir.exists()) originalDir.mkdirs();
        if (!resultDir.exists()) resultDir.mkdirs();
    }

    public String uploadFile(MultipartFile file, String subDir) throws IOException {
        String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();
        String filePath = (subDir.equals("original") ? originalUploadDir : resultOutputDir) + fileName;
        File dest = new File(filePath);
        file.transferTo(dest);
        return filePath;
    }

    public InputStream getFileStream(String filePath) throws FileNotFoundException {
        return new FileInputStream(filePath);
    }

    public boolean fileExists(String filePath) {
        return new File(filePath).exists();
    }
}